//
//  RegisterViewController.m
//  Daybook
//
//  Created by dllo on 16/5/30.
//  Copyright © 2016年 zhangbin. All rights reserved.
//

#import "RegisterViewController.h"
#import "Common.h"
#import <BmobSDK/Bmob.h>
#import "MainViewController.h"

@interface RegisterViewController ()
{
    UITextField *userPhoneNumberTextField;
    UITextField *captchaTextField;
    UITextField *passwordTextField;
    UIButton *getCaptchaButton;
    NSTimer *countDownTimer;
    unsigned secondsCountDown;
}

//@property (nonatomic, strong)UITextField *userPhoneNumberTextField;

//@property (nonatomic, strong)UITextField *captchaTextField;
//
//@property (nonatomic, strong)UITextField *passwordTextField;
//
//
//
//@property (nonatomic, strong)UIButton *getCaptchaButton;
//
//@property (nonatomic, strong)NSTimer *countDownTimer;
//
//@property unsigned secondsCountDown;
@property UITextField *userPhoneNumberTextField;
@property UITextField *captchaTextField;
@property UITextField *passwordTextField;
@property UIButton *getCaptchaButton;
@property NSTimer *countDownTimer;
@property unsigned secondsCountDown;


@end

@implementation RegisterViewController
@synthesize userPhoneNumberTextField;
@synthesize captchaTextField;
@synthesize passwordTextField;
@synthesize getCaptchaButton;
@synthesize countDownTimer;
@synthesize secondsCountDown;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createView];
    
    

    
}


- (void)createView {
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, 34, 25, 25);
    [self.view addSubview:backButton];
    backButton.backgroundColor = [UIColor clearColor];
    
    [backButton setImage:[UIImage imageNamed:@"backArrow"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(clickBack:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
//    UIButton *registerButton  = [UIButton buttonWithType:UIButtonTypeCustom];
//    registerButton.frame = CGRectMake(MAIN_WIDTH - 50, 34, 40, 25);
//    registerButton.backgroundColor = [UIColor whiteColor];
//    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
//    [registerButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
//    [registerButton addTarget:self action:@selector(clickRegister:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:registerButton];
    
    
    self.userPhoneNumberTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, MAIN_WIDTH - 20, 40)];
    self.userPhoneNumberTextField.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.userPhoneNumberTextField];
    
    self.userPhoneNumberTextField.placeholder = @"手机号";
    
    
    self.getCaptchaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.getCaptchaButton.frame = CGRectMake(MAIN_WIDTH - 80, 105, 60, 30);
    self.getCaptchaButton.backgroundColor = [UIColor lightGrayColor];
    [self.getCaptchaButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.getCaptchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.getCaptchaButton.titleLabel.font = [UIFont systemFontOfSize:11];

    self.getCaptchaButton.layer.cornerRadius = 5;
    self.getCaptchaButton.layer.masksToBounds = YES;
    [self.getCaptchaButton addTarget:self action:@selector(getCaptch:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:self.getCaptchaButton];
    
    
    
    
    self.captchaTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 140, MAIN_WIDTH - 20, 40)];
    self.captchaTextField.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.captchaTextField];
    self.captchaTextField.placeholder = @"请输入验证码";
    
    
    
    
    
    self.passwordTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 180, MAIN_WIDTH - 20, 40)];
    self.passwordTextField.backgroundColor = [UIColor whiteColor];
    self.passwordTextField.placeholder = @"请输入密码";
    self.passwordTextField.secureTextEntry = YES;
    [self.view addSubview:self.passwordTextField];
    
    
    
    
    
    UIView *firstLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 100, MAIN_WIDTH, 1)];
    firstLineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:firstLineView];
    
    UIView *secLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 140, MAIN_WIDTH, 1)];
    secLineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:secLineView];
    
    
    UIView *thirdLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 180, MAIN_WIDTH, 1)];
    thirdLineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:thirdLineView];
    
    UIView *fourLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 220, MAIN_WIDTH, 1)];
    fourLineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:fourLineView];
    
    
    UIButton *finishedRegisterButton  = [UIButton buttonWithType:UIButtonTypeCustom];
    finishedRegisterButton.frame = CGRectMake(10, 240, MAIN_WIDTH - 20, 40);
    finishedRegisterButton.backgroundColor  = [UIColor orangeColor];
    [self.view addSubview:finishedRegisterButton];
    
    [finishedRegisterButton setTitle:@"完成注册" forState:UIControlStateNormal];
    [finishedRegisterButton addTarget:self action:@selector(clickFinishRegister:) forControlEvents:UIControlEventTouchUpInside];
    finishedRegisterButton.layer.cornerRadius = 5;
    finishedRegisterButton.layer.masksToBounds = YES;
    
    
    
    
    
}

- (void)getCaptch:(UIButton *)button {
    
    NSString *mobilePhoneNumber = self.userPhoneNumberTextField.text;
    NSLog(@"%@", self.userPhoneNumberTextField.text);
    
    //请求验证码
    [BmobSMS requestSMSCodeInBackgroundWithPhoneNumber:mobilePhoneNumber andTemplate:@"test" resultBlock:^(int number, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
            UIAlertView *tip = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的手机号码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [tip show];
        } else {
            //获得smsID
            NSLog(@"sms ID：%d",number);
            //设置不可点击
            [self setRequestSmsCodeBtnCountDown];
        }
    }];
    
}


-(void)setRequestSmsCodeBtnCountDown{
    [self.self.getCaptchaButton setEnabled:NO];
    self.self.getCaptchaButton.backgroundColor = [UIColor grayColor];
    self.secondsCountDown = 60;
    
    countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownTimeWithSeconds:) userInfo:nil repeats:YES];
    [countDownTimer fire];
}


- (void)clickFinishRegister:(UIButton *)button {
    
    //获取手机号、验证码
    NSString *mobilePhoneNumber = self.userPhoneNumberTextField.text;
    NSString *smsCode = self.captchaTextField.text;
    NSLog(@"%@", smsCode);
    
//    [BmobSMS verifySMSCodeInBackgroundWithPhoneNumber:mobilePhoneNumber andSMSCode:smsCode resultBlock:^(BOOL isSuccessful, NSError *error) {
//        if (isSuccessful) {
//            
//            //修改绑定手机
//            BmobUser *buser = [BmobUser getCurrentUser];
//            buser.mobilePhoneNumber = mobilePhoneNumber;
//            [buser setObject:[NSNumber numberWithBool:YES] forKey:@"mobilePhoneNumberVerified"];
//            [buser updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
//                if (isSuccessful) {
//                    NSLog(@"%@",buser);
//                    UIAlertView *tip = [[UIAlertView alloc] initWithTitle:nil message:@"绑定成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                    [tip show];
//                    
//                    //跳转
//                    MainViewController *mainVC = [[MainViewController alloc]init];
//                    [self.navigationController pushViewController:mainVC animated:YES];
//                    
//                    
//                } else {
//                    NSLog(@"%@",error);
//                }
//            }];
//            
//        } else {
//            NSLog(@"%@",error);
//            UIAlertView *tip = [[UIAlertView alloc] initWithTitle:nil message:@"验证码有误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [tip show];
//        }
//        
//    }];
    
    
//    //验证
//    [BmobSMS verifySMSCodeInBackgroundWithPhoneNumber:mobilePhoneNumber andSMSCode:smsCode resultBlock:^(BOOL isSuccessful, NSError *error) {
//
//    }];
    
    BmobUser *buser = [[BmobUser alloc] init];
    buser.mobilePhoneNumber = self.userPhoneNumberTextField.text;
    buser.password = self.passwordTextField.text;
    
    
    if ([buser.password isEqualToString:@""]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"密码不能为空" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:^{
            
            
        }];
        
    }

    
    
    
    //该方法可以进行注册和登录两步操作，如果已经注册过了就直接进行登录
//    [BmobUser signOrLoginInbackgroundWithMobilePhoneNumber:mobilePhoneNumber andSMSCode:smsCode block:^(BmobUser *user, NSError *error) {
//        if (user) {
//            //user.password = self.passwordTextField.text;
//            
//            
//    
//            //跳转
//
//        } else {
//
//        }
//    }];
    
    
    [buser signUpOrLoginInbackgroundWithSMSCode:smsCode block:^(BOOL isSuccessful, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
            UIAlertView *tip = [[UIAlertView alloc] initWithTitle:nil message:@"验证码有误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [tip show];
        }else {
            self.presentingViewController.view.alpha = 0;
            self.presentingViewController.presentingViewController.view.alpha = 0;
            [self.presentingViewController.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"headChanged" object:nil];
            
        }
        
        
    }];
    
    
    

    
    


    

}


-(void)countDownTimeWithSeconds:(NSTimer*)timerInfo{
    if (secondsCountDown == 0) {
        [self.getCaptchaButton setEnabled:YES];
        self.getCaptchaButton.backgroundColor = [UIColor redColor];
        [self.getCaptchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [countDownTimer invalidate];
    } else {
        [self.getCaptchaButton setTitle:[[NSNumber numberWithInt:secondsCountDown] description] forState:UIControlStateNormal];
        self.secondsCountDown--;
    }
}


- (void)clickBack:(UIButton *)button {

    //[self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
